package com.joiant.community.controller;

import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.joiant.community.dto.PaginationDTO;
import com.joiant.community.dto.QuestionDTO;
import com.joiant.community.mapper.QuestionMapper;
import com.joiant.community.mapper.UserMapper;
import com.joiant.community.model.Question;
import com.joiant.community.model.User;
import com.joiant.community.model.UserExample;
import com.joiant.community.service.QuestionService;

/**
 * 
 * @author joiant
 *
 */
@Controller
public class IndexController {
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private QuestionService questionService;
	
	@GetMapping("/")
	public String index(HttpServletRequest request
			,Model model
			,@RequestParam(name = "page",defaultValue = "1")Integer page
			,@RequestParam(name = "size",defaultValue = "5")Integer size) {
		
		Cookie[] cookies = request.getCookies();
		if(cookies != null && cookies.length > 0) {
			for(Cookie cookie: cookies) {
				if(cookie != null && "token".equals(cookie.getName())) {
					String token = cookie.getValue();
					UserExample userExample = new UserExample();
					userExample.createCriteria().andTokenEqualTo(token);
					
					List<User> users = userMapper.selectByExample(userExample);
					
					if(users != null && users.size() > 0) {
						request.getSession().setAttribute("user", users.get(0));
					}
					break;
				}
			}
		}
		
		PaginationDTO paginationDTO = questionService.list(page,size);
		model.addAttribute("paginationDTO", paginationDTO);
		return "index";
	}
}
